package glpm

import (
	"context"
	"fmt"
	"strings"
)

// AptManager APT包管理器实现
type AptManager struct {
	*BaseManager
}

// NewAptManager 创建APT包管理器
func NewAptManager(config *ManagerConfig) *AptManager {
	base := NewBaseManager("apt", config)
	return &AptManager{
		BaseManager: base,
	}
}

// Install 安装包
func (am *AptManager) Install(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要安装的包名")
	}

	args := []string{"install", "-y"}
	args = append(args, packages...)

	_, err := am.executeCommand(ctx, args...)
	return err
}

// Remove 移除包
func (am *AptManager) Remove(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要移除的包名")
	}

	args := []string{"remove", "-y"}
	args = append(args, packages...)

	_, err := am.executeCommand(ctx, args...)
	return err
}

// Update 更新包列表
func (am *AptManager) Update(ctx context.Context) error {
	_, err := am.executeCommand(ctx, "update")
	return err
}

// Upgrade 升级包
func (am *AptManager) Upgrade(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		// 系统升级
		_, err := am.executeCommand(ctx, "upgrade", "-y")
		return err
	}

	// 升级特定包
	args := []string{"install", "--only-upgrade", "-y"}
	args = append(args, packages...)

	_, err := am.executeCommand(ctx, args...)
	return err
}

// Search 搜索包
func (am *AptManager) Search(ctx context.Context, pattern string) ([]PackageInfo, error) {
	output, err := am.executeCommand(ctx, "search", pattern)
	if err != nil {
		return nil, err
	}

	return am.parseSearchOutput(output)
}

// Info 获取包信息
func (am *AptManager) Info(ctx context.Context, packageName string) (*PackageInfo, error) {
	output, err := am.executeCommand(ctx, "show", packageName)
	if err != nil {
		return nil, err
	}

	return am.parseInfoOutput(output)
}

// ListInstalled 列出已安装的包
func (am *AptManager) ListInstalled(ctx context.Context) ([]PackageInfo, error) {
	output, err := am.executeCommand(ctx, "list", "--installed")
	if err != nil {
		return nil, err
	}

	return am.parseListOutput(output)
}

// IsInstalled 检查指定包是否已安装
func (am *AptManager) IsInstalled(ctx context.Context, packageName string) (bool, error) {
	packages, err := am.ListInstalled(ctx)
	if err != nil {
		return false, err
	}

	for _, pkg := range packages {
		if pkg.Name == packageName {
			return true, nil
		}
	}

	return false, nil
}

// CleanCache 清理包缓存
func (am *AptManager) CleanCache(ctx context.Context) error {
	_, err := am.executeCommand(ctx, "clean")
	return err
}

// AutoRemove 自动移除不需要的包
func (am *AptManager) AutoRemove(ctx context.Context) error {
	_, err := am.executeCommand(ctx, "autoremove", "-y")
	return err
}

// parseSearchOutput 解析搜索输出
func (am *AptManager) parseSearchOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo

	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "Sorting") || strings.HasPrefix(line, "Full Text Search") {
			continue
		}

		// 解析格式: package/version architecture description
		parts := strings.Fields(line)
		if len(parts) >= 3 {
			pkgName := strings.Split(parts[0], "/")[0]

			packages = append(packages, PackageInfo{
				Name:        pkgName,
				Version:     parts[1],
				Description: strings.Join(parts[2:], " "),
			})
		}
	}

	return packages, nil
}

// parseInfoOutput 解析包信息输出
func (am *AptManager) parseInfoOutput(output string) (*PackageInfo, error) {
	info := &PackageInfo{}

	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)

		if strings.HasPrefix(line, "Package:") {
			info.Name = strings.TrimSpace(strings.TrimPrefix(line, "Package:"))
		} else if strings.HasPrefix(line, "Version:") {
			info.Version = strings.TrimSpace(strings.TrimPrefix(line, "Version:"))
		} else if strings.HasPrefix(line, "Architecture:") {
			info.Architecture = strings.TrimSpace(strings.TrimPrefix(line, "Architecture:"))
		} else if strings.HasPrefix(line, "Description:") {
			info.Description = strings.TrimSpace(strings.TrimPrefix(line, "Description:"))
		} else if strings.HasPrefix(line, "Status:") {
			info.Status = strings.TrimSpace(strings.TrimPrefix(line, "Status:"))
		}
	}

	return info, nil
}

// parseListOutput 解析列表输出
func (am *AptManager) parseListOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo

	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "Listing") {
			continue
		}

		// 解析格式: package/version architecture [installed,automatic]
		parts := strings.Fields(line)
		if len(parts) >= 2 {
			pkgName := strings.Split(parts[0], "/")[0]

			status := "installed"
			if len(parts) >= 3 && strings.Contains(parts[2], "automatic") {
				status = "automatic"
			}

			packages = append(packages, PackageInfo{
				Name:    pkgName,
				Version: parts[1],
				Status:  status,
			})
		}
	}

	return packages, nil
}
